/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.edu.thu.laud.cli;

import java.io.File;
import java.io.IOException;
import java.nio.charset.CharacterCodingException;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import jline.ConsoleReader;
import jline.History;

import org.apache.cassandra.thrift.InvalidRequestException;
import org.apache.cassandra.thrift.NotFoundException;
import org.apache.cassandra.thrift.SchemaDisagreementException;
import org.apache.cassandra.thrift.TimedOutException;
import org.apache.cassandra.thrift.UnavailableException;
import org.apache.thrift.TException;
import org.apache.thrift.transport.TTransport;

/**
 * Cassandra Command Line Interface (CLI) Main
 */
public class CliMain
{
	public final static String HISTORYFILE = ".cassandra.history";

	private static TTransport transport = null;
	//   private static Cassandra.Client thriftClient = null;
	//  public  static CliSessionState sessionState = new CliSessionState();
	private static CliClient cliClient;
	private static CliCompleter completer = new CliCompleter();
	private static int lineNumber = 1;





	/**
	 * Disconnect thrift connection to cassandra instance
	 */
	public static void disconnect()
	{
		if (transport != null)
		{
			transport.close();
			transport = null;
		}
	}

	/**
	 * Checks whether the thrift client is connected.
	 * @return boolean - true when connected, false otherwise
	 */
	public static boolean isConnected()
	{
		if(cliClient.connection==null){
			System.out.println("Not connected to a cassandra instance.");
			return false;
		}
		try {
			return !cliClient.connection.isClosed();
		} catch (SQLException e) {
			return false;
		}
	}

	public static void updateCompletor(Set<String> candidates)
	{
		Set<String> actions = new HashSet<String>();
		for (String cf : candidates)
		{
			for (String cmd : completer.getKeyspaceCommands())
				actions.add(String.format("%s %s", cmd, cf));
		}

		String[] strs = Arrays.copyOf(actions.toArray(), actions.toArray().length, String[].class);

		completer.setCandidateStrings(strs);
	}

	public static void processStatement(String query) throws CharacterCodingException, ClassNotFoundException, TException, TimedOutException, SchemaDisagreementException, NotFoundException, InvalidRequestException, NoSuchFieldException, UnavailableException, IllegalAccessException, InstantiationException, SQLException
	{
		cliClient.executeCLIStatement(query);
	}

	public static void processStatementInteractive(String query)
	{
		try
		{
			cliClient.executeCLIStatement(query);
		}
		catch (Exception e)
		{
			//String errorTemplate = sessionState.inFileMode() ? "Line " + lineNumber + " => " : "";
			String errorTemplate ="";
			Throwable exception = (e.getCause() == null) ? e : e.getCause();
			String message = (exception instanceof InvalidRequestException) ? ((InvalidRequestException) exception).getWhy() : e.getMessage();

			System.err.println(errorTemplate + message);

			if (!(e instanceof RuntimeException))
				e.printStackTrace(System.err);

			if (cliClient.state.batch || cliClient.state.inFileMode())
			{
				System.exit(4);
			}
		}
		finally
		{
			lineNumber++;
		}
	}

	public static void main(String args[]) throws IOException, ClassNotFoundException, SQLException
	{
		// process command line arguments
		cliClient=new CliClient(args);

		// connect to laud server.
		try
		{
			cliClient.connect();   
		}
		catch (RuntimeException e)
		{
			System.err.println(e.getMessage());
			System.exit(-1);
		}

//		// load statements from file and process them
//		if (sessionState.inFileMode())
//		{
//			FileReader fileReader;
//
//			try
//			{
//				fileReader = new FileReader(sessionState.filename);
//			}
//			catch (IOException e)
//			{
//				sessionState.err.println(e.getMessage());
//				return;
//			}
//
//			evaluateFileStatements(new BufferedReader(fileReader));
//			return;
//		}

		ConsoleReader reader = new ConsoleReader();
		if(cliClient.state.debug){
			jline.WindowsTerminal winTerm=(jline.WindowsTerminal)reader.getTerminal();
			winTerm.setDirectConsole(false);
		}
		
//		if (!sessionState.batch)
//		{
			reader.addCompletor(completer);
			reader.setBellEnabled(false);

			String historyFile = System.getProperty("user.home") + File.separator + HISTORYFILE;

			try
			{
				History history = new History(new File(historyFile));
				reader.setHistory(history);
			}
			catch (IOException exp)
			{
				System.err.printf("Unable to open %s for writing %n", historyFile);
			}

//		}
//		else if (!sessionState.verbose) // if in batch mode but no verbose flag
//		{
//			sessionState.out.close();
//		}

		cliClient.printBanner();

		String prompt;
		String line = "";
		String currentStatement = "";
		boolean inCompoundStatement = false;

		while (line != null)
		//while(true)
		{
			prompt = (inCompoundStatement) ? "...\t" : getPrompt(cliClient);

			try
			{
				
				line = reader.readLine(prompt);
			}
			catch (IOException e)
			{
				// retry on I/O Exception
			}

			if (line == null)
				return;
			
			line = line.trim();

			// skipping empty and comment lines
			if (line.isEmpty() || line.startsWith("--"))
				continue;

			currentStatement += line;

			if (line.endsWith(";") || line.equals("?"))
			{
				processStatementInteractive(currentStatement);
				currentStatement = "";
				inCompoundStatement = false;
			}
			else
			{
				currentStatement += " "; // ready for new line
				inCompoundStatement = true;
			}
		}
	}

//	private static void evaluateFileStatements(BufferedReader reader) throws IOException
//	{
//		String line = "";
//		String currentStatement = "";
//
//		boolean commentedBlock = false;
//
//		while ((line = reader.readLine()) != null)
//		{
//			line = line.trim();
//
//			// skipping empty and comment lines
//			if (line.isEmpty() || line.startsWith("--"))
//				continue;
//
//			if (line.startsWith("/*"))
//				commentedBlock = true;
//
//			if (line.startsWith("*/") || line.endsWith("*/"))
//			{
//				commentedBlock = false;
//				continue;
//			}
//
//			if (commentedBlock) // skip commented lines
//				continue;
//
//			currentStatement += line;
//
//			if (line.endsWith(";"))
//			{
//				processStatementInteractive(currentStatement);
//				currentStatement = "";
//			}
//			else
//			{
//				currentStatement += " "; // ready for new line
//			}
//		}
//	}

	/**
	 * Returns prompt for current connection
	 * @param client - currently connected client
	 * @return String - prompt with username and keyspace (if any)
	 */
	private static String getPrompt(CliClient client)
	{
		return "[" + client.state.username + "@" + client.state.keyspace + "] ";
	}

}